今天開始讓我來連續一個禮拜的leetcode刷題吧!直接來看今天的題目:
/*
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example 1:
Input: [1,2,3]
Output: 6
Example 2:
Input: [1,2,3,4]
Output: 24
Note:
The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.
*/
var maximumProduct = function(nums) {
};
這題需要從一個數字陣列中找出三個數字相乘的結果為最大。
解題思考:
剛開始在看的時候直覺想說
所以一開始這樣寫:
var maximumProduct = function(nums) {
let ascending = nums.sort((a, b) => a - b)
let result = ascending[nums.length -1]* ascending[nums.length -2]* ascending[nums.length -3]
return result
};
但後來submit後被打臉,完全忘記考慮負數的情況,舉例來說:輸入是[60,-3,-1,-4] 經過排序[-4,-3,-1,60],最後三個相乘是180,但預期結果是720。
再次思考
var maximumProduct = function(nums) {
let ascending = nums.sort((a, b) => a - b)
let firstCase = ascending[nums.length -1]* ascending[nums.length -2]* ascending[nums.length -3]
let secondCase = ascending[0] * ascending[1] * ascending[nums.length - 1]
return Math.max(firstCase, secondCase)
};
以上是今天內容!